1 Data and package

library(scran)
library(SingleCellExperiment)
library(scater)
library(scattermore)
library(moon)
library(ggplot2)
library(ggthemes)
library(ggpubr)
library(reshape2)
library(dplyr)
library(stringr)
library(pheatmap)
library(CellChat)
library(gridExtra)
library(RColorBrewer)
meta_liao <- readRDS("results/liao_results/meta_liao.rds")
coldata_liao <- readRDS("results/liao_results/coldata_liao.rds")
severity_color <- c("#2ca02c", "#FFD92F", "#7570B3")
names(severity_color) <- c("healthy control", "mild", "severe")
# CCI results (Cellchat)
cellchat_res_list <- readRDS("results/liao_results/liao_cellchat_res_list.rds")

2 Overall pattern analysis

rankNet_byCellType <- function(object, slot.name = "netP", 
                               x.rotation = 90, title = NULL, color.use = NULL, 
                               bar.w = 0.75, font.size = 8) 
{
    object1 <- methods::slot(object, slot.name)
    prob1 = object1$prob
    df <- melt(apply(prob1, 3, function(x) {
        df <- melt(x)
        colnames(df) <- c("Ligand", "Receptor", "value")
        df
    }))
    df <- df[, c("Ligand", "Receptor", "L1", "value")]
    colnames(df)[3] <- "Pathway"
    return(df)
    
    
}
rankNet_byCellType_list <- lapply(cellchat_res_list, rankNet_byCellType)

rankNet_byCellType_list <- melt(rankNet_byCellType_list)
rankNet_byCellType_list$Ligand_group <- unlist(lapply(strsplit(as.character(rankNet_byCellType_list$Ligand), 
                                                               "_"), "[[", 1))
rankNet_byCellType_list$Receptor_group <- unlist(lapply(strsplit(as.character(rankNet_byCellType_list$Receptor), 
                                                                 "_"), "[[", 1))


saveRDS(rankNet_byCellType_list, file = "results/liao_results/rankNet_byCellType_list_liao.rds")
rankNet_byGroup_agg <- aggregate(rankNet_byCellType_list$value, 
                                 list(rankNet_byCellType_list$Ligand_group,
                                      rankNet_byCellType_list$Receptor_group,
                                      rankNet_byCellType_list$L1,
                                      rankNet_byCellType_list$Pathway),
                                 sum)


colnames(rankNet_byGroup_agg) <- c("Ligand_group", 
                                   "Receptor_group",
                                   "sample",
                                   "Pathway",
                                   "value")
features <- paste(rankNet_byGroup_agg$Ligand_group,
                  rankNet_byGroup_agg$Receptor_group,
                  rankNet_byGroup_agg$Pathway, sep = "_")

rankNet_byGroup_agg$features <- features
rankNet_byGroup_agg_all <- dcast2(rankNet_byGroup_agg, 
                                  features ~ sample, 
                                  fun.aggregate = sum, value.var = "value")
rankNet_byGroup_agg_all <- rankNet_byGroup_agg_all[rowSums(rankNet_byGroup_agg_all) > 0, ]
rankNet_byGroup_agg_all <- rankNet_byGroup_agg_all[rowSums(rankNet_byGroup_agg_all!=0) > 2, ]

2.1 Feature selction: kruskal test

kruskal_pvalue <- list()
for (i in 1:nrow(rankNet_byGroup_agg_all)) {
    #if (i %% 100 == 0) print(i)
    
    kruskal_res <- try(kruskal.test(unlist(rankNet_byGroup_agg_all[i,]) ~ meta_liao[colnames(rankNet_byGroup_agg_all), ]$Condition2), silent = TRUE)
    kruskal_pvalue[[i]] <- try(kruskal_res$p.value, silent = TRUE)
    
}

kruskal_pvalue <- lapply(kruskal_pvalue, function(x) {
    if (class(x) == "try-error") {
        x <- NULL
    }
    x
})
names(kruskal_pvalue) <- rownames(rankNet_byGroup_agg_all)
kruskal_pvalue <- unlist(kruskal_pvalue)

kruskal_pvalue <- p.adjust(kruskal_pvalue, method = "BH")

saveRDS(kruskal_pvalue, "results/liao_results/CCI_kruskal_pvalue_condition_liao.rds")

2.2 PCA

pca_patient <- prcomp(t(-1/log(rankNet_byGroup_agg_all[names(kruskal_pvalue[kruskal_pvalue < 0.2]),])), 
                      scale. = TRUE, center = TRUE)
library(ggrepel)
pca1 <- ggplot(data.frame(pca_patient$x), aes(x = pca_patient$x[, 1],
                                              y = pca_patient$x[, 2],
                                              color = meta_liao[rownames(pca_patient$x),]$Condition2)) +
    geom_point(size = 4, alpha = 0.8) +
    # geom_text_repel(aes(label = rownames(pca_patient$x))) +
    theme_yx() +
    theme(aspect.ratio = 1) +
    scale_color_manual(values = severity_color) +
    xlab("PCA1") +
    ylab("PCA2") +
    labs(color = "")

pca2 <- ggplot(data.frame(pca_patient$x), aes(x = pca_patient$x[, 1],
                                              y = pca_patient$x[, 3],
                                              color = meta_liao[rownames(pca_patient$x),]$Condition2)) +
    geom_point(size = 3, alpha = 0.8) +
    # geom_text_repel(aes(label = rownames(pca_patient$x))) +
    theme_yx() +
    theme(aspect.ratio = 1) +
    scale_color_manual(values = severity_color) +
    xlab("PCA1") +
    ylab("PCA3") +
    labs(color = "")

pca3 <- ggplot(data.frame(pca_patient$x), aes(x = pca_patient$x[, 2],
                                              y = pca_patient$x[, 3],
                                              color = meta_liao[rownames(pca_patient$x),]$Condition2)) +
    geom_point(size = 3, alpha = 0.8) +
    # geom_text_repel(aes(label = rownames(pca_patient$x))) +
    theme_yx() +
    theme(aspect.ratio = 1) +
    scale_color_manual(values = severity_color) +
    xlab("PCA2") +
    ylab("PCA3") +
    labs(color = "")

ggarrange(pca1, pca2, pca3, align = "hv", 
          common.legend = TRUE, ncol = 2, nrow = 2)

pca1_label <- ggplot(data.frame(pca_patient$x), aes(x = pca_patient$x[, 1],
                                                    y = pca_patient$x[, 2],
                                                    color = meta_liao[rownames(pca_patient$x),]$Condition2)) +
    geom_point(size = 3, alpha = 0.8) +
    geom_text_repel(aes(label = rownames(pca_patient$x))) +
    theme_bw() +
    theme(aspect.ratio = 1) +
    scale_color_manual(values = severity_color) +
    xlab("PCA1") +
    ylab("PCA2") +
    labs(color = "")

2.3 Aggregation by samples

aff_mat_bySample <- lapply(split(rankNet_byGroup_agg, rankNet_byGroup_agg$sample),
                           function(x) dcast2(x, Ligand_group~Receptor_group,
                                              fun.aggregate = mean, value.var = "value"))
all_cellTypes <- names(table(coldata_liao$pred_cellTypes_scClassify))

aff_mat_bySample <- lapply(aff_mat_bySample, function(x) {
    mat <- matrix(0, ncol = length(all_cellTypes), nrow = length(all_cellTypes))
    colnames(mat) <- rownames(mat) <- all_cellTypes
    mat[rownames(x), colnames(x)] <- as.matrix(x)
    mat
})

aff_mat_bySample <- lapply(aff_mat_bySample, function(x) {
    (x - min(x))/(max(x) - min(x))
})


p <- lapply(1:length(aff_mat_bySample), function(i) {
    pheatmap(aff_mat_bySample[[i]],
             cluster_cols = FALSE, 
             cluster_rows = FALSE,
             main = names(aff_mat_bySample)[i],
             color =  colorRampPalette(c("white", 
                                         brewer.pal(n = 7, 
                                                    name = "Reds")))(100))
})

pdf("figures/LiaoEtAl/cellchat_CCI_network_sample_byCellType.pdf", 
    width = 15, height = 10)
do.call(grid.arrange, list(grobs = lapply(p, function(x) x$gtable), ncol = 3))
dev.off()
## quartz_off_screen 
##                 2
# 


severe_patients <- rownames(meta_liao)[meta_liao$Condition2 == "severe"]
aff_mat_severe <- Reduce("+", aff_mat_bySample[names(aff_mat_bySample) %in% severe_patients])/length(severe_patients)

moderate_patients <- rownames(meta_liao)[meta_liao$Condition2 == "mild"]
aff_mat_moderate <- Reduce("+", aff_mat_bySample[names(aff_mat_bySample) %in% moderate_patients])/length(moderate_patients)

control_patients <- rownames(meta_liao)[meta_liao$Condition2 == "healthy control"]
aff_mat_control <- Reduce("+", aff_mat_bySample[names(aff_mat_bySample) %in% control_patients])/length(control_patients)

p_severe <- pheatmap(aff_mat_severe, cluster_cols = FALSE, 
                     cluster_rows = FALSE,
                     main = "severe (average across samples)",
                     color =  colorRampPalette(c("white", 
                                                 brewer.pal(n = 7, 
                                                            name = "Reds")))(100),
                     breaks = seq(0, max(aff_mat_severe), max(aff_mat_severe)/100))

library(RColorBrewer)
p_moderate <- pheatmap(aff_mat_moderate, 
                       cluster_cols = FALSE, 
                       cluster_rows = FALSE,
                       main = "moderate (average across samples)",
                       color =  colorRampPalette(c("white", 
                                                   brewer.pal(n = 7, 
                                                              name = "Reds")))(100),
                       breaks = seq(0, max(aff_mat_severe), max(aff_mat_severe)/100))

p_control <- pheatmap(aff_mat_control, 
                      cluster_cols = FALSE, 
                      cluster_rows = FALSE,
                      main = "control (average across samples)",
                      color =  colorRampPalette(c("white", 
                                                  brewer.pal(n = 7, 
                                                             name = "Reds")))(100),
                      breaks = seq(0, max(aff_mat_control), max(aff_mat_control)/100))

pdf("figures/LiaoEtAl/cellchat_CCI_network_byCondition_noScale.pdf", 
    width = 12, height = 4)
do.call(grid.arrange, list(grobs = list(p_control$gtable,
                                        p_moderate$gtable,
                                        p_severe$gtable), ncol = 3))
dev.off()
## quartz_off_screen 
##                 2
aff_mat_diff <- aff_mat_severe - aff_mat_moderate

keep <- intersect(names(which(colSums(aff_mat_diff) != 0)),
                  names(which(rowSums(aff_mat_diff) != 0)))

pheatmap(aff_mat_diff[keep, keep],
         cluster_cols = FALSE, 
         cluster_rows = FALSE,
         color =  colorRampPalette(c("blue", "white", "red"))(100)[c(seq(1, 35, 5),
                                                                     36:100)],
         main = "server - moderate (Liao et al.)",
         #file = "figures/LiaoEtAl/cellchat_CCI_network_byCondition_diff_noScale.pdf",
         width = 8,
         height = 7)

3 Pathway-cluster cell-cell interaction

3.1 Monocyte -> Neutrophil

keep_Monocyte <- rankNet_byCellType_list$Receptor_group %in% "Neutrophil" &
    rankNet_byCellType_list$Ligand_group %in% c("Monocyte")

pmat_Monocytes_neutrophil <- rankNet_byCellType_list[keep_Monocyte, ] %>%
    dcast2(Pathway~L1, 
           fun.aggregate = sum, value.var = "value")
pmat_Monocytes_neutrophil <- pmat_Monocytes_neutrophil[rowSums(pmat_Monocytes_neutrophil) != 0 &
                                                           rowSums(pmat_Monocytes_neutrophil != 0) > 1, ]

chua_pathway_clust_monocytes <- readRDS("results/chua_results/cellchat_LigandMonocyte_ReceptorNeutrophils_pathway_cluster.rds")


anno_row <- data.frame(pathway_cluster = factor(chua_pathway_clust_monocytes))

rownames(anno_row) <- names(chua_pathway_clust_monocytes)
anno_color <- list()
anno_color$pathway_cluster <- RColorBrewer::brewer.pal(length(table(anno_row)), "Set2")
names(anno_color$pathway_cluster) <- seq_len(length(table(anno_row)))
pmat_Monocytes_neutrophil <- pmat_Monocytes_neutrophil[rownames(pmat_Monocytes_neutrophil) %in% names(chua_pathway_clust_monocytes),]
chua_pathway_clust_monocytes <- chua_pathway_clust_monocytes[rownames(pmat_Monocytes_neutrophil)]
pmat_Monocytes_neutrophil <- pmat_Monocytes_neutrophil[names(chua_pathway_clust_monocytes)[order(chua_pathway_clust_monocytes, rowMeans(pmat_Monocytes_neutrophil))],]
pheatmap(-1/log(pmat_Monocytes_neutrophil),
         #annotation_col = anno_col,
         annotation_colors = anno_color,
         annotation_row = anno_row,
         clustering_method = "ward.D2",
         cluster_cols = FALSE,
         cluster_rows = FALSE,
         color = colorRampPalette(c("white", 
                                    brewer.pal(n = 9, name = "Reds")))(100),
         main = "Ligand: Monocytes; Recetpor: Neutrophils (Liao et al.)",
         #file = "figures/LiaoEtAl/cellchat_LigandMonocyte_ReceptorNeutrophils_heatmap.pdf",
         height = 12,
         width = 6
)

4 Session Info

sessionInfo()
## R version 4.0.2 RC (2020-06-20 r78727)
## Platform: x86_64-apple-darwin17.0 (64-bit)
## Running under: macOS Catalina 10.15.7
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_AU.UTF-8/en_AU.UTF-8/en_AU.UTF-8/C/en_AU.UTF-8/en_AU.UTF-8
## 
## attached base packages:
## [1] parallel  stats4    stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] ggrepel_0.8.2               RColorBrewer_1.1-2         
##  [3] gridExtra_2.3               CellChat_0.0.1             
##  [5] bigmemory_4.5.36            pheatmap_1.0.12            
##  [7] stringr_1.4.0               dplyr_1.0.2                
##  [9] reshape2_1.4.4              ggpubr_0.3.0               
## [11] ggthemes_4.2.0              moon_0.1.0                 
## [13] scattermore_0.6             scater_1.16.1              
## [15] ggplot2_3.3.2               scran_1.16.0               
## [17] SingleCellExperiment_1.10.1 SummarizedExperiment_1.18.1
## [19] DelayedArray_0.14.0         matrixStats_0.56.0         
## [21] Biobase_2.48.0              GenomicRanges_1.40.0       
## [23] GenomeInfoDb_1.24.2         IRanges_2.22.2             
## [25] S4Vectors_0.26.1            BiocGenerics_0.34.0        
## 
## loaded via a namespace (and not attached):
##   [1] readxl_1.3.1              backports_1.1.8          
##   [3] circlize_0.4.10           systemfonts_0.2.3        
##   [5] NMF_0.30.1                plyr_1.8.6               
##   [7] igraph_1.1.0              BiocParallel_1.22.0      
##   [9] listenv_0.8.0             gridBase_0.4-7           
##  [11] digest_0.6.25             foreach_1.5.0            
##  [13] htmltools_0.5.0           viridis_0.5.1            
##  [15] ggalluvial_0.12.0         magrittr_1.5             
##  [17] cluster_2.1.0             doParallel_1.0.15        
##  [19] openxlsx_4.1.5            limma_3.44.3             
##  [21] sna_2.5                   ComplexHeatmap_2.4.2     
##  [23] globals_0.12.5            svglite_1.2.3.2          
##  [25] colorspace_1.4-1          haven_2.3.1              
##  [27] xfun_0.18                 crayon_1.3.4             
##  [29] RCurl_1.98-1.2            jsonlite_1.6.1           
##  [31] bigmemory.sri_0.1.3       iterators_1.0.12         
##  [33] glue_1.4.1                registry_0.5-1           
##  [35] gtable_0.3.0              zlibbioc_1.34.0          
##  [37] XVector_0.28.0            GetoptLong_1.0.0         
##  [39] car_3.0-8                 BiocSingular_1.4.0       
##  [41] future.apply_1.5.0        shape_1.4.4              
##  [43] abind_1.4-5               scales_1.1.1             
##  [45] edgeR_3.30.3              rngtools_1.5             
##  [47] bibtex_0.4.2.2            rstatix_0.6.0            
##  [49] Rcpp_1.0.4.6              viridisLite_0.3.0        
##  [51] xtable_1.8-4              clue_0.3-57              
##  [53] reticulate_1.16           dqrng_0.2.1              
##  [55] foreign_0.8-80            rsvd_1.0.3               
##  [57] FNN_1.1.3                 ellipsis_0.3.1           
##  [59] farver_2.0.3              pkgconfig_2.0.3          
##  [61] locfit_1.5-9.4            labeling_0.3             
##  [63] tidyselect_1.1.0          rlang_0.4.9              
##  [65] munsell_0.5.0             cellranger_1.1.0         
##  [67] tools_4.0.2               generics_0.0.2           
##  [69] statnet.common_4.3.0      broom_0.7.2              
##  [71] evaluate_0.14             yaml_2.2.1               
##  [73] knitr_1.30                zip_2.0.4                
##  [75] purrr_0.3.4               dendextend_1.13.4        
##  [77] pbapply_1.4-2             future_1.17.0            
##  [79] compiler_4.0.2            beeswarm_0.2.3           
##  [81] curl_4.3                  png_0.1-7                
##  [83] ggsignif_0.6.0            tibble_3.0.4             
##  [85] statmod_1.4.34            stringi_1.4.6            
##  [87] RSpectra_0.16-0           gdtools_0.2.2            
##  [89] forcats_0.5.0             lattice_0.20-41          
##  [91] Matrix_1.2-18             vctrs_0.3.5              
##  [93] pillar_1.4.4              lifecycle_0.2.0          
##  [95] GlobalOptions_0.1.2       BiocNeighbors_1.6.0      
##  [97] data.table_1.12.8         cowplot_1.0.0            
##  [99] bitops_1.0-6              irlba_2.3.3              
## [101] R6_2.4.1                  network_1.16.0           
## [103] rio_0.5.16                vipor_0.4.5              
## [105] codetools_0.2-16          assertthat_0.2.1         
## [107] pkgmaker_0.31.1           rjson_0.2.20             
## [109] withr_2.2.0               GenomeInfoDbData_1.2.3   
## [111] hms_0.5.3                 grid_4.0.2               
## [113] coda_0.19-3               tidyr_1.1.2              
## [115] rmarkdown_2.4             DelayedMatrixStats_1.10.0
## [117] carData_3.0-4             ggbeeswarm_0.6.0